<!doctype html>
<!--[if lt IE 7]>
<html lang="en-US" class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>
<html lang="en-US" class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>
<html lang="en-US" class="no-js lt-ie9""> <![endif]-->
<!--[if gt IE 8]><!-->
<html lang="en-US" class="no-js"> <!--<![endif]-->
<head>
	<title>PINPOINT</title>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate" />
	<meta http-equiv="expires" content="0" />
	<meta http-equiv="pragma" content="no-cache" />
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width">
	<link rel="shortcut icon" href="favicon.png" type="image/png">
	<link rel="icon" href="favicon.png" type="image/png">
	<link rel="stylesheet" href="components/bootstrap/dist/css/bootstrap.min.css?v=${buildTime}">
	<link rel="stylesheet" href="styles/timer.css?v=${buildTime}">
	<style>
		.starter-template {
			padding: 40px 15px;
			text-align: center;
		}
		.main-navbar {
			position: absolute;
			margin: 0px 0 0 0;
			height: 40px;
			min-height: 40px;
			background-color: #252a3a;
			width: 100%;
			border-radius: 0px;
		}
		.main-navbar .navbar-brand {
			padding: 7px 15px;
		}
		.navbar .beta {
			position: absolute;
			left: 138px;
			top: 12px;
			font-size: 12px;
			color: rgb(216, 33, 33);
		}
		.loading {
			position:absolute;
			top: 0px;
			width:100%;
			height:100%;
			background: rgba(255, 255, 255, .5);
			text-align:center;
		}
		td {
			padding: 2px;
		}
		td.agents div { padding: 2px; }

	</style>
</head>
<body>
<div class="navbar main-navbar bs-docs-nav">
	<div class="nav-container">
		<a href="/" class="navbar-brand"><img class="brand" src="/images/logo2.png" width="116" height="18"><div class="beta">beta</div></a>
	</div>
</div>

<div class="container">
	<div class="starter-template">
		<h1>Pinpoint Agent...</h1>
		<div id='dashboard'></div>
	</div>
	<table class="table table-striped" id="agentList">
		<thead>
		<tr>
			<th>Group Number</th>
			<th>#</th>
			<th>Application Name</th>
			<th></th>
			<th>Agent List</th>
		</tr>
		</thead>
		<tbody></tbody>
	</table>
</div>

<div class="loading" id="loadingBar">
	<div class="timer-loader" style="margin-top:40%"></div>
</div>

<script src="components/jquery/dist/jquery.js?v=${buildTime}"></script>
<script src="components/bootstrap/dist/js/bootstrap.min.js?v=${buildTime}"></script>
<script src="components/handlebars/handlebars.min.js?v=${buildTime}"></script>
<script src="components/moment/moment.js?v=${buildTime}"></script>

<script>
	var GROUP_COUNT = 20;
	var oRef = {
		REQ_URL: "/applications.pinpoint",
		fnTableTemplate : Handlebars.compile([
			'<tr id="{{{appNameID}}}">',
				'{{#if visible}}<td rowspan="{{rowSpan}}">{{{groupNumber}}}</td>{{/if}}',
				'<td>{{{index}}}</td>',
				'<td data-app-name="{{{appName}}}@{{{serviceType}}}">{{{appName}}}@{{{serviceType}}}</td>',
				'<td>{{#if visible}}<button type="button" class="btn btn-info retrieve" data-group-number="{{groupNumber}}">Retrieve  {{groupNumber}} group</button>{{/if}}</td>',
				'<td class="agents"></td>',
			'</tr>'
		].join("")),
		$tbody: $("tbody")
	};

	var aApplicationList, htRemoveTargetAgent = {};
	$.ajax({
		url: oRef.REQ_URL,
		method: "GET",
		dataType: "json"
	}).done( function(data){ //, textStatue, jqXHR) {
		if ( typeof data["exception"] === "undefined" ) {
			aApplicationList = data;
			addToTable(data);
			initEvent();
		} else {
			alert( data["exception"].message );
		}
		$("#loadingBar").hide();
	}).fail(function(jqXHR, textStatus, errorThrown) {});


	function initEvent() {
		$("table").on("click", "button.retrieve", function () {
			loadAgentList( parseInt( $(this).attr("data-group-number") ) );
			$(this).addClass("disabled");
		}).on("click", "button.remove", function() {
			removeAgent( $(this) );
		});
	}
	function addToTable( data ) {
		for( var i = 0 ; i < data.length ; i++ ) {
			var oApplication = data[i];
			oRef.$tbody.append( oRef.fnTableTemplate({
				index: i + 1,
				visible: i % GROUP_COUNT === 0,
				rowSpan: GROUP_COUNT,
				appName: oApplication.applicationName,
				appNameID: makeAppID( oApplication.applicationName + oApplication.serviceType ),
				groupNumber: parseInt( i / GROUP_COUNT ),
				serviceType: oApplication.serviceType
			}));
		}
	}
	function loadAgentList(  groupNumber ) {
		$("#loadingBar").show();
		var start = groupNumber * GROUP_COUNT;
		var end = start + GROUP_COUNT;

		makeInactiveAgentCall( start, end );
	}
	function makeInactiveAgentCall( start, end ) {
		requestInactiveAgent( aApplicationList[start].applicationName, function( agentHash ) {
			requestInactiveAgentCallback( aApplicationList[start].applicationName, aApplicationList[start].serviceType,  agentHash );
			start++;
			if ( start < end ) {
				makeInactiveAgentCall( start, end );
			} else {
				$("#loadingBar").hide();
			}
		});
	}
	function requestInactiveAgent( appName, callback ) {
		$.ajax({
			url: "/admin/getInactiveAgents.pinpoint?password=admin&applicationName=" + appName,
			method: "GET",
			dataType: "json"
		}).done(function ( agentHash ) { //, textStatue, jqXHR) {
			if (typeof agentHash["exception"] === "undefined") {
				callback( agentHash );
			} else {
				alert(data["exception"].message);
			}
		}).fail(function (jqXHR, textStatus, errorThrown) {});
	}
	function requestInactiveAgentCallback( appName, serviceType, agentHash ) {
		htRemoveTargetAgent[ appName ] = agentHash;
		addAgent( appName, serviceType, agentHash );
	}
	function addAgent( appName, serviceType, agentHash ) {
		var agentCount = 0;
		for( var p in agentHash ) {
			agentCount++;
			$("#" + makeAppID( appName + serviceType ) + " td.agents").append('<div class="' + convertDot(p) + '">' + p + ' <button type="button" class="btn btn-danger btn-xs remove" data-application-name="' + appName + '" data-agent-id="' + p + '">remove</button></div>');
		}
		if ( agentCount === 0 ) {
			$("#" + makeAppID( appName + serviceType ) + " td.agents").append('<div>none</div>');
		}
	}
	function removeAgent( $elButton ) {
		$("#loadingBar").show();
		var appName = $elButton.attr("data-application-name");
		var agentID = $elButton.attr("data-agent-id");

		$.ajax({
			url: "/admin/removeAgentId.pinpoint",
			method: "post",
			data: {
				"agentId": agentID,
				"password": "admin",
				"applicationName": appName
			},
			dataType: "json"
		}).done(function ( result ) { //, textStatue, jqXHR) {
			if (typeof result["exception"] === "undefined") {
				if ( result === "OK" ) {
					var aRelatedApp = htRemoveTargetAgent[appName][agentID];
					var aRemoveAppName = [ appName ];
					for( var i = aRelatedApp.length - 1 ; i >= 0 ; i-- ) {
						var o = aRelatedApp[i];
						var $elAgent = $("#" + makeAppID( o.applicationName + o.serviceType ) + " ." + convertDot(agentID) );
						var $elParent= $elAgent.parent();
						if ( $elAgent.length > 0 ) {
							$elAgent.remove();
							aRemoveAppName.push( o.applicationName );

							if ( $elParent.find("> div").length === 0 ) {
								$elParent.append('<div>none</div>');
							}
						}
						aRelatedApp.splice( i, 1 );
					}
					for( var j = 0 ; j < aRemoveAppName.length ; j++ ) {
						var removeAppName = aRemoveAppName[j];
						if ( typeof htRemoveTargetAgent[removeAppName] !== "undefined" && typeof htRemoveTargetAgent[removeAppName][agentID] !== "undefined" ) {
							delete htRemoveTargetAgent[removeAppName][agentID];
						}
					}
				}
			} else {
				alert(data["exception"].message);
			}
			$("#loadingBar").hide();
		}).fail(function (jqXHR, textStatus, errorThrown) {});
	}
	function makeAppID( applicationID ) {
		return "row_" + convertDot( applicationID );
	}
	function convertDot( str ) {
		return str.replace(/\./g, "___");
	}
</script>
</body>
</html>
